package com.tjetc.dao.impl;

import com.tjetc.dao.OrderDao;
import com.tjetc.domain.Order;
import com.tjetc.domain.Record;
import com.tjetc.utils.Db;
import com.tjetc.utils.PageInfo;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Date;
import java.sql.SQLException;
import java.util.List;

public class OrderDaoImpl implements OrderDao {
    @Override
    public Order listDocOrder(Date date, String time, int did) throws SQLException {
        return Db.runner0().query("select * from `order` where date = ? and time = ? and did = ?",
                new BeanHandler<>(Order.class),date,time,did);
    }

    @Override
    public void addOrder(Order order) throws SQLException {
        Db.runner0().update("insert into `order` (uid, did, date,time) values (?,?,?,?)",
                order.getUid(),order.getDid(),order.getDate(),order.getTime());
    }

    @Override
    public List<Order> listMyOrder(PageInfo<Order> pageInfo, int did,int status) throws SQLException {
        return Db.runner0().query("select * from `order` where did = ? and status = ? order by date desc,status asc limit ?,?",
                new BeanListHandler<>(Order.class),did,status,
                pageInfo.getStartRecord(),pageInfo.getPageSize());
    }

    @Override
    public int getCount(int did,int status) throws SQLException {
        return ((Long)Db.runner0().query("select count(id) from `order` where did = ? and status = ?",
                new ScalarHandler<>(),did,status)).intValue();
    }

    @Override
    public void updateStatusById(int id) throws SQLException {
         Db.runner().update(Db.getConnection(),"update `order` set status = 1 where id = ?",id);
    }

    @Override
    public Order findByDid(int id) throws SQLException {
        return Db.runner0().query("select * from `order` where did=?",
                new BeanHandler<>(Order.class),id);
    }

    @Override
    public List<Order> listInOrder(int did, Date date, String time) throws SQLException {
        return Db.runner0().query("select * from `order` where did = ? and date = ? and time < ?",
                new BeanListHandler<>(Order.class),did,date,time);
    }

    @Override
    public List<Order> listUserOrder(int uid) throws SQLException {
        return Db.runner0().query("select * from `order` where uid = ? and status = 0",
                new BeanListHandler<>(Order.class),uid);
    }

    @Override
    public List<Order> listMyOrderTime(int did, Date date) throws SQLException {
        return Db.runner0().query("select * from `order` where did = ? and `date` = ?",
                new BeanListHandler<>(Order.class),did,date);
    }

}
